package com.sanpu.kxe.business.trade.view;

import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.orhanobut.dialogplus.DialogPlus;
import com.orhanobut.dialogplus.OnItemClickListener;
import com.sanpu.library.imagechoose.utils.PermissionsConstant;
import com.sanpu.library.imagechoose.utils.PermissionsUtils;
import com.sanpu.kxe.R;
import com.sanpu.kxe.base.BaseTitleActivity;
import com.sanpu.kxe.business.main.adapter.ShareAdapter;
import com.sanpu.kxe.business.main.bean.UserCenterOutput;
import com.sanpu.kxe.business.main.view.MainActivity;
import com.sanpu.kxe.business.trade.bean.PayOrderOutput;
import com.sanpu.kxe.business.trade.contract.PaymentQRcodeContract;
import com.sanpu.kxe.business.trade.contract.TradeConfig;
import com.sanpu.kxe.business.trade.presenter.PaymentQRcodePresenter;
import com.sanpu.kxe.common.cache.CacheManage;
import com.sanpu.kxe.common.cache.CacheModel;
import com.sanpu.kxe.common.enums.PayType;
import com.sanpu.kxe.common.utils.QRCode;
import com.sanpu.kxe.module.specialunit.SimplifySpanBuild;
import com.sanpu.kxe.module.specialunit.unit.SpecialClickableUnit;
import com.sanpu.kxe.module.specialunit.unit.SpecialTextUnit;
import com.sanpu.kxe.utils.AppContextUtil;
import com.sanpu.kxe.utils.ToastUtil;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Description：付款二维码等待扫码页面(扫码收款)
 * Created by 薛勇军 on 2018/8/1.
 */

public class PaymentQRcodeActivity extends BaseTitleActivity implements PaymentQRcodeContract.View {

    @Bind(R.id.amt)
    TextView vAmt;
    @Bind(R.id.des)
    TextView vDes;
    @Bind(R.id.image)
    ImageView vImage;
    @Bind(R.id.screen_clip_layout)
    LinearLayout vClipLayout;

    private ShareAdapter mShareAdapter;

    private PaymentQRcodeContract.Presenter mPresenter;

    private String mCodeUrl;

    private Bitmap mQrcodeBitmap, mClipScreen;

    private PayType mPayType;

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_payment_qrcode;
    }

    @Override
    protected void initView() {
        super.initView();
        commonTitle.showRightTextView("保存");
        mShareAdapter = new ShareAdapter(mContext);

        String vipOpenId = getIntent().getStringExtra(TradeConfig.INTENT_VIPOPENID);
        boolean isUpgrade = false;
        if (!TextUtils.isEmpty(vipOpenId)) {
            commonTitle.setTitle("支付二维码");
            isUpgrade = true;
        } else {
            commonTitle.setTitle("扫码收款");
        }

        String amt = getIntent().getStringExtra(TradeConfig.INTENT_AMOUNT);
        mPayType = (PayType) getIntent().getSerializableExtra(TradeConfig.INTENT_PAYTYPE);
        String rlId = getIntent().getStringExtra(TradeConfig.INTENT_RLID);

        if (TextUtils.isEmpty(amt) || mPayType == null) {
            ToastUtil.showTextViewPrompt("二维码获取失败！");
            return;
        }

        SimplifySpanBuild build = new SimplifySpanBuild(this, vAmt, "付款金额：");
        build.appendSpecialUnit(new SpecialTextUnit(amt, Color.parseColor("#F7511E")));
        build.appendSpecialUnit(new SpecialTextUnit("元"));
        vAmt.setText(build.build());

        UserCenterOutput retDatBean = CacheManage.getInstance().getCache(CacheModel.USER_CENTER_KEY);
        String name = retDatBean != null ? retDatBean.getNickName() : "";

        SimplifySpanBuild desBuild = new SimplifySpanBuild(this, vDes);
        if (!TextUtils.isEmpty(vipOpenId)) {
            if (mPayType == PayType.UNIONPAY) {
                desBuild.appendSpecialUnit(new SpecialTextUnit("您正在充值会员；请使用", Color.parseColor("#909090")));
                desBuild.appendSpecialUnit(new SpecialTextUnit("银行APP或云闪付APP").setSpecialClickableUnit(new SpecialClickableUnit(null).showUnderline()).setSpecialTextColor(ContextCompat.getColor(mContext, R.color.color_base)));
                desBuild.appendSpecialUnit(new SpecialTextUnit("的扫一扫来支付。", Color.parseColor("#909090")));
            } else {
                desBuild.appendSpecialUnit(new SpecialTextUnit("您正在充值会员；因", Color.parseColor("#909090")));
                desBuild.appendSpecialUnit(new SpecialTextUnit(mPayType.getTarget()).setSpecialClickableUnit(new SpecialClickableUnit(null).showUnderline()).setSpecialTextColor(ContextCompat.getColor(mContext, R.color.color_base)));
                desBuild.appendSpecialUnit(new SpecialTextUnit("限制，扫一扫不支持从相册获取付款，请直接通过扫一扫扫二维码来支付。", Color.parseColor("#909090")));
            }
        } else {
            desBuild.appendSpecialUnit(new SpecialTextUnit(name, Color.parseColor("#F7511E")));
            desBuild.appendSpecialUnit(new SpecialTextUnit("正在向您发起一笔金额为￥" + amt + "的收款，请使用", Color.parseColor("#909090")));
            desBuild.appendSpecialUnit(new SpecialTextUnit(mPayType == PayType.UNIONPAY ? "银行APP、云闪付APP" : mPayType.getTarget()).setSpecialClickableUnit(new SpecialClickableUnit(null).showUnderline()).setSpecialTextColor(ContextCompat.getColor(mContext, R.color.color_base)));
            desBuild.appendSpecialUnit(new SpecialTextUnit("扫码功能进行支付!", Color.parseColor("#909090")));
        }
        vDes.setText(desBuild.build());

        mPresenter = new PaymentQRcodePresenter(this, isUpgrade);
        mPresenter.payOrder(amt, rlId, vipOpenId);
    }

    @Override
    public void showDataView(PayOrderOutput orderOutput) {
        if (orderOutput != null) {
            mCodeUrl = orderOutput.getCodeUrl();
            createBitmap();
            vImage.setImageBitmap(mQrcodeBitmap);
            vClipLayout.setDrawingCacheEnabled(true);
            mClipScreen = vClipLayout.getDrawingCache();
        }
    }

    @Override
    protected void setListener() {
        super.setListener();
        commonTitle.setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!PermissionsUtils.checkWriteStoragePermission(PaymentQRcodeActivity.this))
                    return;
                save();
            }
        });
    }

    @OnClick({R.id.home, R.id.share})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.home:
                AppContextUtil.finishAllExclByActivity(MainActivity.class.getName());
                break;
            case R.id.share:
                share();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        mPresenter.getTranPayStatus();
    }

    /**
     * 生成二维码图片
     */
    private void createBitmap() {
        if (!TextUtils.isEmpty(mCodeUrl)) {
            if (mPayType.getIcon() != 0 && mPayType != PayType.UNIONPAY) {
                mQrcodeBitmap = QRCode.createQRCodeWithLogo5(
                        mCodeUrl, 500, BitmapFactory.decodeResource(getResources(), mPayType.getIcon()));
            } else {
                mQrcodeBitmap = QRCode.createQRCode(mCodeUrl);
            }
        }
    }

    /**
     * 保存图片
     */
    private void save() {
        if (mQrcodeBitmap == null || mQrcodeBitmap.isRecycled()) {
            createBitmap();
            vImage.setImageBitmap(mQrcodeBitmap);
        }
        if (TextUtils.isEmpty(mCodeUrl)) {
            return;
        }
        if (mClipScreen == null) {
            vClipLayout.setDrawingCacheEnabled(true);
            mClipScreen = vClipLayout.getDrawingCache();
        }
        mPresenter.saveImage(mClipScreen, mPayType.getTarget());
    }

    /**
     * 分享
     */
    private void share() {
        DialogPlus dialog = DialogPlus.newDialog(this)
                .setAdapter(mShareAdapter)
                .setHeader(R.layout.view_dialogplus_header)
                .setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(DialogPlus dialog, Object item, View view, int position) {
                        if (position < 0) return;
                        if (TextUtils.isEmpty(mCodeUrl)) {
                            ToastUtil.showTextViewPrompt("二维码没有生成，无法分享！");
                            return;
                        }
                        if (mClipScreen == null) {
                            vClipLayout.setDrawingCacheEnabled(true);
                            mClipScreen = vClipLayout.getDrawingCache();
                        }

                        mPresenter.shareImage(mClipScreen, mShareAdapter.getItem(position).getPlatform());
                    }
                })
                .setExpanded(false)  // This will enable the expand feature, (similar to android L share dialog)
                .create();
        dialog.show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            switch (requestCode) {
                case PermissionsConstant.REQUEST_EXTERNAL_WRITE:
                    if (PermissionsUtils.checkWriteStoragePermission(this)) {
                        save();
                    }
                    break;
            }
        }
    }

    @Override
    protected boolean hasBindEventBus() {
        return false;
    }

    @Override
    public void setPresenter(PaymentQRcodeContract.Presenter presenter) {
        this.mPresenter = presenter;
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.onDestroyPresenter();
            mPresenter = null;
        }
        try {
            if (mQrcodeBitmap != null && !mQrcodeBitmap.isRecycled()) {
                mQrcodeBitmap.isRecycled();
                mQrcodeBitmap = null;
            }

            if (mClipScreen != null && !mClipScreen.isRecycled()) {
                mClipScreen.isRecycled();
                mClipScreen = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
